package organisms;

import java.util.Iterator;

import processing.core.PApplet;
import field.AngleField;
import field.Field;
import geom.Line;
import geom.Segment;
import geom.Vector;

public abstract class Organism {
	public static int currentId = 0;
	public int id;
	protected Vector pos;
	Vector prevPos;
	protected Line trace;
	PApplet pa;
	Vector worldStart; 
	Vector worldEnd;
	boolean draw = true;
	
	boolean alive;
	
	
	public Organism(PApplet pa, Vector pos, Vector worldStart, Vector worldEnd) {
		super();
		setTrace(new Line(pa, this));
		this.setPos(pos);
		this.pa = pa;
		this.worldStart = worldStart;
		this.worldEnd = worldEnd;
		currentId++;
		id = currentId;
		
		alive = true;
	}

	public void reset(Vector pos){
		setTrace(new Line(pa, this));
		this.setPos(pos);
		alive = true;
	}

	public boolean isAlive(){
		if(!alive) return false;
		if(getPos().x > worldEnd.x || getPos().x < worldStart.x ||
		   getPos().y > worldEnd.y || getPos().y < worldStart.y){
			if(alive) PApplet.println("died at coords " + getPos());
			alive = false;		
		}
		return alive;
	}

	
	public void setPos(Vector pos){
		prevPos = this.pos;
		this.pos = pos;
		
		getTrace().addPoint(pos.getCopy());

		
	}
	
	public boolean ignoreSegment(Segment s){
		if(s.getParent().getParent() == null)
			return false;
		if(!s.getParent().getParent().equals(this))
			return false;
		return true;
	}
	
	public abstract void move();
	public abstract void draw();
	
	public void drawTrace() {
		if(!draw) return;
		pa.noFill();
		pa.stroke(200, 120, 120, 100);
		if(prevPos != null)pa.line(prevPos.x, prevPos.y, getPos().x, getPos().y);
	}

	public Vector getPos() {
		return pos;
	}


	public void setTrace(Line trace) {
		this.trace = trace;
	}


	public Line getTrace() {
		return trace;
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((pos == null) ? 0 : pos.hashCode());
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Organism))
			return false;
		final Organism other = (Organism) obj;
		if (id != other.id)
			return false;
		if (pos == null) {
			if (other.pos != null)
				return false;
		} else if (!pos.equals(other.pos))
			return false;
		return true;
	}
	
	
}
